﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Linq;

namespace SlamCms.SharePoint.Publishing.WebParts
{
    public partial class PublisherManagerControl : UserControl
    {

        public int PageSize { get; set; }

        public string Keywords { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ltKeywords.Text = Keywords;
            this.ltPageSize.Text = PageSize.ToString();

            Page.ClientScript.RegisterClientScriptInclude("jquery", ResolveUrl("~/_layouts/inc/jquery-1.6.2.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("datatables", ResolveUrl("~/_layouts/inc/jquery.dataTables.js"));
            Page.ClientScript.RegisterClientScriptInclude("datatablesPlugins", ResolveUrl("~/_layouts/inc/dataTables.plugins.js"));

            AddCssInclude("/Style Library/SlamCMS/css/SlamCMS_table.css");


            this.ltInitScript.Text = String.Format("<script type=\"text/javascript\">{0}</script>", GetInitScript());
        }

        private void AddCssInclude(string url)
        {
            string include = String.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" media=\"all\" />", ResolveUrl(url));
            if (!Page.Header.Controls.Cast<Control>().OfType<LiteralControl>().Any(c => c.Text == include))
            {
                Page.Header.Controls.Add(new LiteralControl(include));
            }
        }

        private string GetInitScript()
        {
            StringBuilder builder = new StringBuilder();

            string asInitValsVar = "asInitVals_" + this.ClientID;
            string configurationVar = "configuration_" + this.ClientID;

            builder.AppendLine("var "+asInitValsVar+" = new Array();");
            builder.AppendLine("var " + configurationVar + " = new ControlConfiguration('" + settingsContainer.ClientID + "', '" + controlsContainer.ClientID + "'," + asInitValsVar + ");");

            //builder.AppendLine("InitUploader(" + uploaderVar + ", " + settingsVar + ");");
            //builder.AppendLine("InitUploader(" + settingsVar + ");");

            //builder.AppendLine(String.Format("$(document).ready("+settingsVar+".DocumentReady({0}));", uploaderVar));
            builder.AppendLine("$(document).ready(" + configurationVar + ".documentReady());");


            return builder.ToString();
        }
    }
}
